package com.jams.goodox.activity.serve.enterprise;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.resp.ReviewAuthorizationResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.permission.PhoneUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import retrofit2.Call;

/**
 * 企业通讯录
 */
public class EnterPriseAddressBookActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.empty_view)
    LoadView emptyView;
    @Bind(R.id.refresh)
    RefreshRecyclerView refresh;
    @Bind(R.id.sfl)
    SwipeRefreshLayout sfl;
    private int curPage;
    private int clickItemPosition = -1;//用来记录点击的标记，详情页删除回调局部刷新
    List<ReviewAuthorizationResp.DataBean.ResultListBean> dataList = new ArrayList<>();
    RecycleCommonAdapter<ReviewAuthorizationResp.DataBean.ResultListBean> mAdapter;
    public static final String ENTERPRISE_ADDRESS_BOOK_ENTERPRISE_ID ="ENTERPRISE_ADDRESS_BOOK_ENTERPRISE_ID";
    /**
     * 企业id
     */
    private String enterpriseId;
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_enter_prise_address_book;
    }

    @Override
    protected void init() {
        final Intent i= getIntent();
        enterpriseId = StringUtils.newString(i.getStringExtra(ENTERPRISE_ADDRESS_BOOK_ENTERPRISE_ID));
        sfl.setOnRefreshListener(this);
        StyleUtil.titleBackKey(this, "企业通讯录");
        refresh.setLayoutManager(new RefreshLinearLayoutManager(this));
        refresh.setHasFixedSize(true);
        mAdapter = new RecycleCommonAdapter<ReviewAuthorizationResp.DataBean.ResultListBean>(this, dataList, R.layout.item_address_book) {
            @Override
            public void convert(RecycleCommonViewHolder helper, ReviewAuthorizationResp.DataBean.ResultListBean item, int position) {
                setData(helper, item, position);
            }
        };

        //增加headView
        View v = new View(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dp2px(mContext, 15));
        v.setLayoutParams(params);
        mAdapter.setHeaderView(v);
        refresh.setAdapter(mAdapter);
        refresh.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                // 开启线加载更多数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                });
            }
        });
        refresh.addItemDecoration(new RecyclerDivider(
                mContext, LinearLayoutManager.VERTICAL, 3, ContextCompat.getColor(this, R.color.shallow_divider)));
        onRefresh();
    }

    //获取通讯录列表
    private void getData() {
        Map<String,String> param = new HashMap<>();
        param.put("curPage", curPage + "");
        param.put("enterpriseId", enterpriseId);
        param.put("pageSize", AppConfig.PagSize + "");
        param.put("status", "1");//已授权
        enqueue(createCallService(EnterpriseService.class).reviewAuthorization(param), new RetrofitCallbackListener<ReviewAuthorizationResp>() {
            @Override
            public void onSuccess(Call<ReviewAuthorizationResp> call, ReviewAuthorizationResp result) {
                try {
                    sfl.setRefreshing(false);
                    refresh.loadMoreComplete();
                    if (result.data != null) {
                        if (curPage == 1) {
                            dataList.clear();
                        }
                        if (result.data.pageInfo == null) {
                            refresh.setCanLoadMore(false);
                        } else {
                            refresh.setCanLoadMore(result.data.pageInfo.hasMore);
                        }
                        dataList.addAll(result.data.resultList);
                        curPage++;
                        refresh.notifyData();
                    }
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_data);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                sfl.setRefreshing(false);
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                }else {
                    emptyView.loadComplete();
                }
            }
        });
    }

    //设置item数据
    private void setData(RecycleCommonViewHolder helper, final ReviewAuthorizationResp.DataBean.ResultListBean item, int position) {
        if (1 == item.sex) {
            helper.setBackground(R.id.sex, R.mipmap.male_icon);
        } else if (2 == item.sex) {
            helper.setBackground(R.id.sex, R.mipmap.female_icon);
        }
        helper.setSimpleDraweeView(R.id.head, StringUtils.newString(item.headPicName))
                .setText(R.id.tv_customer_name, item.userName)
                .getView(R.id.iv_message_mail);
        
        helper.getView(R.id.iv_customer_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhoneUtils phoneUtils = new PhoneUtils(mContext);
                phoneUtils.makeCall(item.userName+"",item.mobileNum+"");
            }
        });
        if(StringUtils.newString(item.userId).equals(StringUtils.newString(DataCacheManager.getInstance().getUser().getUserId()))){
            helper.setViewVisible(R.id.iv_message_mail,false).setViewVisible(R.id.iv_customer_phone,false);
        }else{
            helper.setViewVisible(R.id.iv_message_mail,true).setViewVisible(R.id.iv_customer_phone,true);
        }
        helper.getView(R.id.iv_message_mail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    sfl.setRefreshing(true);
                    curPage = 1;
                    getData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    
}
